//
// main.cpp for \ in /home/jousse_f//workspace/C++/abstractVM
// 
// Made by florian jousseau
// Login   <jousse_f@epitech.net>
// 
// Started on  Mon Feb  6 12:40:18 2012 florian jousseau
// Last update Fri Apr 13 15:35:47 2012 florian jousseau
//

#include <fstream>
#include <cstdlib>
#include <iostream>
#include "Parser.hh"
#include "Abstract.hh"
#include "Exception.hh"

void		action(Parser *p, VM & S);

static int	startWithFile(std::string &file)
{
  VM		S;
  Parser	*p = new Parser;

  std::string	line;
  int		i = 0;

  try
    {
      while (file[i + 1])
	{
	  line = "";
	  while (file[i] && file[i] != '\n')
	    line += file[i++];
	  p->toParse(line);
	  action(p, S);
	  i++;
	}
      if (S.getParser()->getExit() == 0)
	throw AbstractEx("[Error] No Exit end of file");
    }
  catch (AbstractEx& e)
    {
      std::string	error = e.what();
      if (error == "")
	return EXIT_SUCCESS;
      std::cerr << e.what() << std::endl;
      return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}

int	main(int ac, char **av)
{
  std::string		line;
  std::string		file;
  std::fstream		instr;

  if (ac == 1)
    {
      while (line != ";;")
      	{
	  getline(std::cin, line, '\n');
	  file += line;
	  file += '\n';
	}
    }
  else if (ac == 2)
    {
      instr.open(av[1]);
      if (!instr.is_open())
	{
	  std::cerr << "[Error] Cannot open file " << av[1] << std::endl;
	  return EXIT_FAILURE;
	}
      while (getline(instr, line, '\n'))
	file += line += '\n';
    }
  return (startWithFile(file));
}
